﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EasierRdp.Models;
using EasierRdp.Util;

namespace EasierRdp
{
    partial class AddUserDialog : Form
    {
        public RdpGroup Group { get; set; }
        public RdpServer Server { get; set; }

        public AddUserDialog()
        {
            InitializeComponent();
            this.DialogResult = DialogResult.None;
        }

        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == EasierRdpEvents.UserDialog.ShowDialog(EasierRdpEvents.MainForm))
            {
                RebindList();
            }
        }

        private void AddServerDialog_Load(object sender, EventArgs e)
        {
            RebindList();
        }

        private void RebindList()
        {
            UserList.Items.Clear();
            foreach (var user in RdpContext.Users)
            {
                var index = UserList.Items.Add(user.Value);
                if ((Server != null && Server.Users.Any(s => s.Id == user.Key))
                    || (Group != null && Group.Servers.Any(s => s.Id == user.Key)))
                {
                    UserList.SetItemChecked(index, true);
                }
            }
        }

        private void ButtonOk_Click(object sender, EventArgs e)
        {
            var users = UserList.CheckedItems.Cast<RdpUser>().ToList();
            var userRefs = users.Select(r => new RdpUserRef(r.Id)).ToList();
            if (Server != null)
            {
                Server.Users.Clear();
                foreach (var item in userRefs)
                {
                    Server.Users.Add(item);
                }
                foreach (var rdpUser in users)
                {
                    if (rdpUser.Servers.All(s => s.Id != Server.Id))
                    {
                        rdpUser.Servers.Add(new RdpServerRef(Server.Id));
                    }
                }
            }
            if (Group != null)
            {
                Group.Servers.Clear();
                foreach (var item in users)
                {
                    Group.Users.Add(item);
                }
            }
            EasierRdpEvents.RebindTreeView();
            this.DialogResult = DialogResult.OK;
        }

        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
    }
}
